<template>
  <je-modal
    v-model:visible="visibleSource"
    width="660px"
    height="auto"
    :title="sourceObj.id === '' ? $t('sourceModel.addSource') : $t('sourceModel.updateSource')"
    class="win-module"
    :resize="false"
    :maximizable="false"
    cancel-button
    :ok-button="saveSource"
    @close="cancelSource"
  >
    <div class="modal-source-box">
      <je-form :label-col="{ style: 'width:62px;margin-left:-10px;' }">
        <je-form-item :label="$t('sourceModel.sourceName')" v-bind="validateInfos.name">
          <je-input v-model:value="sourceObj.name" @change="changeName" />
        </je-form-item>
        <je-form-item :label="$t('sourceModel.sourceCode')" v-bind="validateInfos.code">
          <je-input v-model:value="sourceObj.code" />
        </je-form-item>
        <je-form-item :label="$t('sourceModel.sourceType')" v-bind="validateInfos.type">
          <je-radio-group v-model:value="sourceObj.type" :cols="1" wrap :options="typeOptions" />
        </je-form-item>
        <je-form-item :label="$t('sourceModel.sourceRemark')">
          <je-text-area
            v-model:value="sourceObj.remark"
            :rows="4"
            :placeholder="$t('sourceModel.sourceRemark')"
          />
        </je-form-item>
      </je-form>
    </div>
  </je-modal>
</template>

<script>
  import { defineComponent, reactive, toRefs, onMounted } from 'vue';
  import { Input, Modal, Form, Radio } from '@jecloud/ui';
  import { pinyin } from '@jecloud/utils';
  import { verifyData, sourceTypeOpitons } from '@/helper/common';
  import { saveSourceAndModule, updateSourceAndModule } from '@/api/index';
  import { SourceTypeAndIcon } from '@/helper/constant';
  const useForm = Form.useForm;
  export default defineComponent({
    name: 'ModalSource',
    components: {
      JeModal: Modal,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeInput: Input,
      JeRadioGroup: Radio.Group,
      JeTextArea: Input.TextArea,
    },
    props: {
      sourceData: {
        type: Object,
        default: () => ({
          id: '',
          name: '',
          code: '',
          type: 'VIEW', //类型
          remark: '', //备注
        }),
      },
      parentId: {
        type: String,
        default: () => '',
      },
      productId: {
        type: String,
        default: () => '',
      },
    },
    emits: ['loadTreeAndSelect', 'cancelEditSource'],
    setup(props, { emit }) {
      const state = reactive({
        visibleSource: true,
        sourceObj: { ...props.sourceData },
        rules: {
          name: verifyData.name,
          code: verifyData.code,
          type: [verifyData.required],
        },
        //类型选项
        typeOptions: sourceTypeOpitons,
      });
      const { resetFields, validate, validateInfos } = useForm(state.sourceObj, state.rules, {
        onValidate: (...args) => {},
      });
      const methods = {
        //保存/编辑数据源
        saveSource({ $modal, button }) {
          const modal = $modal,
            btn = button;
          btn.loading = true;
          validate()
            .then(() => {
              //新增
              if (!props.sourceData.id && !props.sourceData.name && !props.sourceData.code) {
                const params = {
                  tableCode: 'JE_CORE_DATASOURCE', //表编码
                  funcCode: 'JE_CORE_DATASOURCE', //功能编码
                  DATASOURCE_TEXT: state.sourceObj.name, //名称
                  DATASOURCE_CODE: state.sourceObj.code, //编码
                  DATASOURCE_TYPE: state.sourceObj.type, //类型
                  DATASOURCE_REMARK: state.sourceObj.remark, //备注
                  SY_PARENT: props.parentId || '', //父id
                  SY_PRODUCT_ID: props.productId, //产品ID
                };
                //根据数据源类型设置对应icon图标
                SourceTypeAndIcon.forEach((sourceTypeItem) => {
                  if (sourceTypeItem.type == state.sourceObj.type) {
                    params.DATASOURCE_ICON = sourceTypeItem.icon;
                  }
                });
                saveSourceAndModule(params).then((res) => {
                  if (res.success) {
                    //关闭弹窗
                    btn.loading = false;
                    modal.close();
                    methods.resetModule();
                    Modal.notice('新建数据源成功', 'success');
                    // emit('loadSourceTree');
                    emit('loadTreeAndSelect', res.data.dynaBean);
                  } else {
                    btn.loading = false;
                    Modal.alert(res.message, 'error');
                  }
                });
              } else {
                //编辑
                const params = {
                  tableCode: 'JE_CORE_DATASOURCE',
                  funcCode: 'JE_CORE_DATASOURCE',
                  JE_CORE_DATASOURCE_ID: state.sourceObj.id,
                  DATASOURCE_TEXT: state.sourceObj.name,
                  DATASOURCE_CODE: state.sourceObj.code,
                };
                updateSourceAndModule(params).then((res) => {
                  if (res.success) {
                    //关闭弹窗
                    btn.loading = false;
                    modal.close();
                    methods.resetModule();
                    Modal.notice(res.message, 'success');
                    emit('loadSourceTree');
                  } else {
                    btn.loading = false;
                    Modal.alert(res.message, 'error');
                  }
                });
              }
            })
            .catch((error) => {
              btn.loading = false;
            });
          return false;
        },
        //关闭弹窗
        cancelSource() {
          state.visibleModule = false;
          methods.resetModule();
          emit('cancelEditSource');
        },
        //初始化数据
        resetModule() {
          resetFields();
          state.sourceObj = {
            id: '', //模块id
            name: '', //模块名称
            code: '', //模块编码
          };
        },
        //name值改变触发
        changeName() {
          state.sourceObj.code = pinyin(state.sourceObj.name, 'PY');
        },
      };
      onMounted(() => {});
      return {
        resetFields,
        validateInfos,
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style scoped lang="less">
  .modal-source-box {
    width: 100%;
  }
</style>
